package com.mhc.suzuki.controller;

import com.mhc.haval.security.model.User;
import com.mhc.suzuki.constant.ErrorCodeEnum;
import com.subaru.common.entity.BizResult;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Optional;

/**
 * @author Churry
 * @create 2017-09-01 11:52
 **/
@Slf4j
@Controller
public class LoginController {

    /**
     * 重定向到首页，如果已经登录，返回登录用户的信息
     *
     * @return
     */
    @ApiOperation(value = "重定向到首页", notes = "重定向到首页，如果已经登录，返回登录用户的信息")
    @RequestMapping(value ={"/index", "/"}, method = RequestMethod.GET)
        public String index(@AuthenticationPrincipal User logedUser, ModelMap modelMap) {
        Optional<User> userOptional = Optional.ofNullable(logedUser);
        if (userOptional.isPresent()) {
            modelMap.put("user", logedUser);
        }
        return "index";
    }

    /**
     * 获取登录用户详情
     * @param logedUser
     * @return
     */
    @RequestMapping(value = "/user/detail", method = RequestMethod.GET)
    @ResponseBody
    public Object getUserInfo(@AuthenticationPrincipal User logedUser) {
        Optional<User> userOptional = Optional.ofNullable(logedUser);
        return userOptional.map((user) -> BizResult.create(user, true, ErrorCodeEnum.SUCCESS.getErrCode(), ErrorCodeEnum.SUCCESS.getErrMsg()))
                .orElse(BizResult.create(ErrorCodeEnum.SYS_ERROR.getErrCode(), ErrorCodeEnum.SYS_ERROR.getErrMsg()));
    }

}
